<template>
	<el-dialog title="员工授权" v-model="visible" :width="860" destroy-on-close @closed="$emit('closed')">
		<el-container style="border: 0; overflow-y: hidden">
			<el-main style="padding: 0">
				<el-container style="border: 1px solid rgb(228, 231, 237)">
					<el-aside style="width: 250px" v-show="isOrgState">
						<el-header>机构列表</el-header>
						<el-container style="height: 80%;">
							<el-main>
								<el-input v-model="groupFilterText" placeholder="名称" />
								<el-tree ref="tree" class="menu" node-key="id" :data="group" :current-node-key="''"
									:highlight-current="true" :expand-on-click-node="false" default-expand-all="true"
									:filter-node-method="groupFilterNode" @node-click="handleNodeClick"></el-tree>
							</el-main>
						</el-container>
						<!-- <el-container>
							<el-header>机构列表</el-header>
							<el-main>
								<el-radio-group v-model="currentOrgCode" @change="loadUserRole">
									<el-radio :label="item.id" :key="item.id" style="width: 180px"
										v-for="item in orgList">
										{{ item.label }}
									</el-radio>
								</el-radio-group></el-main>
						</el-container> -->
					</el-aside>
					<el-container>
						<el-header>角色列表<el-checkbox v-model="checkAll" :indeterminate="isIndeterminate"
								@change="handleCheckAllChange" label="全选" size="large" /></el-header>
						<el-main>
							<el-checkbox-group v-model="currentRole" @change="handleCheckedRoleChange">
								<el-checkbox :label="item.id" :key="item.id" style="width: 180px"
									v-for="item in roleList">
									{{ item.label }}
								</el-checkbox>
							</el-checkbox-group>
						</el-main>
					</el-container>
					<el-aside>
						<el-container style="overflow-y: hidden">
							<el-header>权限树</el-header>
							<el-main>
								<div style="
										width: 268px;
										height: 602px;
										overflow: scroll;
										overflow-y: scroll;
										overflow-x: hidden;
									">
									<el-tree style="width: 266px" ref="treeRef" :data="treeData" show-checkbox
										default-expand-all node-key="id" highlight-current :props="defaultProps"
										v-bind:disabled="true" />
								</div>
							</el-main>
						</el-container>
					</el-aside>
				</el-container>
			</el-main>
			<el-footer style="
					border: 0;
					padding-top: 20px;
					text-align: center;
					height: inherit;
				">
				<el-button type="primary" @click="submit()">保存</el-button>
				<el-button @click="visible = false">关闭</el-button>
			</el-footer>
		</el-container>
	</el-dialog>
</template>

<script>
import publicjs from "@/api/model/publicjs";
import TreeUtils from "@/api/model/TreeUtils";
export default {
	name: "layoutLCR",
	data() {
		return {
			defaultProps: {
				children: "children",
				label: "name",
				disabled: this.disabledFn, //禁用方法
			},
			groupFilterText: "",
			group: [],
			showGrouploading: false,
			currentNodeKey: null,
			defaultCheck: [],
			visible: true,
			checkAll: false,
			isIndeterminate: true,
			//已经授权的机构
			currentOrgList: [],
			//当前选择的机构
			currentOrgCode: "",
			//当前选择的角色，只有code(id)
			currentRole: [],
			//所有的机构列表
			orgList: [],
			//所有的角色列表,存储id和label
			roleList: [],
			//所有的角色列表，只存储id，主要配个全选择使用
			roleCodeList: [],
			//加载权限树
			treeData: [],
			//当前人员编码
			userCode: "",
			//当前人员姓名
			userName: "",
			//权限类型
			purviewType:"0",
			//是否显示机构
			isOrgState:true,
		};
	},
	watch: {
		groupFilterText(val) {
			this.$refs.tree.filter(val);
		},
	},
	methods: {
		open(type,orgCode="") {
			this.purviewType=type
			if(orgCode){
				this.currentOrgCode=orgCode;
				this.isOrgState=false;
			}
			return this;
		},
		disabledFn(data) {
			console.log(data)
			//if(data.childList.length>0){   //可以根据数据来做判断禁止功能
			return true
			//}
		},
		setData(rowData) {
			this.userCode = rowData.Code;
			this.userName = rowData.Name;
		},
		handleCheckAllChange(val) {
			// eslint-disable-next-line no-debugger
			debugger;
			this.currentRole = val ? this.roleCodeList : [];
			this.isIndeterminate = false;
			this.LoadRolePurview();
		},
		handleCheckedRoleChange(value, v2) {
			// eslint-disable-next-line no-debugger
			debugger;
			console.log(v2);
			let checkedCount = value.length;
			this.checkAll = checkedCount === this.roleCodeList.length;
			this.isIndeterminate =
				checkedCount > 0 && checkedCount < this.roleCodeList.length;
			this.LoadRolePurview();
		},

		async loadOrgList() {
			var head = new publicjs.head();
			publicjs.initHead(head, "query");
			// eslint-disable-next-line no-undef
			let ed = new publicjs.entitydata(head);
			var eo = new publicjs.entityobj();
			eo.AttrList = {
				Name: "Organize",
				UseDistinct: false,
				OrgCode: "",
				UseBackUp: false,
				UseGroup: false,
			};
			eo.ValueList = {
				Code: "id",
				Name: "label",
			};
			eo.QueryList = { State: "1", Visible: "1" };
			ed.Data.Content.ObjectList.Object.push(eo);
			try {
				var returnValueStr = await this.$API.auth.objProcess.post(ed);
				var returnValue = JSON.parse(returnValueStr);
				// eslint-disable-next-line no-debugger
				debugger;
				if (returnValue.Result.OpFlag == "1") {
					let returnObj =
						returnValue.Result.Content.ObjectList.Object.Rows.Row;
					this.orgList = returnObj;
					ed = null;
					eo = null;
					head = null;
				}
			} catch (error) {
				this.loading = false;
				//this.emptyText = error.statusText;
				return false;
			}
		},
		async loadRoleList() {
			var head = new publicjs.head();
			publicjs.initHead(head, "query");
			// eslint-disable-next-line no-undef
			let ed = new publicjs.entitydata(head);
			var eo = new publicjs.entityobj();
			eo.AttrList = {
				Name: "Role",
				UseDistinct: false,
				OrgCode: "",
				UseBackUp: false,
				UseGroup: false,
			};
			eo.ValueList = {
				Code: "id",
				Name: "label",
			};
			eo.QueryList = { State: "1" };
			ed.Data.Content.ObjectList.Object.push(eo);
			try {
				var returnValueStr = await this.$API.auth.objProcess.post(ed);
				var returnValue = JSON.parse(returnValueStr);
				// eslint-disable-next-line no-debugger
				debugger;
				if (returnValue.Result.OpFlag == "1") {
					let returnObj =
						returnValue.Result.Content.ObjectList.Object.Rows.Row;
					this.roleList = returnObj;
					for (let index in this.roleList) {
						this.roleCodeList.push(this.roleList[index].id);
					}
					ed = null;
					eo = null;
					head = null;
				}
			} catch (error) {
				this.loading = false;
				//this.emptyText = error.statusText;
				return false;
			}
		},
		async loadPurviewTree() {
			var head = new publicjs.head();
			publicjs.initHead(head, "query");
			// eslint-disable-next-line no-undef
			let ed = new publicjs.entitydata(head);
			var eo = new publicjs.entityobj();
			eo.AttrList = {
				Name: "Purview",
				UseDistinct: false,
				OrgCode: "",
				UseBackUp: false,
				UseGroup: false,
			};
			eo.ValueList = {
				Id: "id",
				Name: "name",
				ParentId: "parentid",
			};
			eo.QueryList = { State: "1" ,PurviewType: this.purviewType };
			ed.Data.Content.ObjectList.Object.push(eo);
			try {
				var returnValueStr = await this.$API.auth.objProcess.post(ed);
				var returnValue = JSON.parse(returnValueStr);
				// eslint-disable-next-line no-debugger
				debugger;
				if (returnValue.Result.OpFlag == "1") {
					let returnObj =
						returnValue.Result.Content.ObjectList.Object;
					let format = {
						id: "id", //菜单编号，作为树形查找id
						root: "00", //顶层节点的parentId是root
						pid: "parentid", //父节点标识字段为parentId
						child: "children", //构造出的树形子节点数组名为children
						sort: { field: "id", direct: 1 },
					}; //排序字段为sortNo，且正序
					let result = TreeUtils.treetool.format(
						returnObj.Rows.Row,
						format
					);
					this.treeData = result;

					ed = null;
					eo = null;
					head = null;
				}
			} catch (error) {
				this.loading = false;
				//this.emptyText = error.statusText;
				return false;
			}
		},
		async LoadRolePurview() {
			// eslint-disable-next-line no-debugger
			debugger;
			this.$refs.treeRef.setCheckedKeys([]);
			if (this.currentRole.length == 0) return;
			var head = new publicjs.head();
			publicjs.initHead(head, "query");
			// eslint-disable-next-line no-undef
			let ed = new publicjs.entitydata(head);
			var eo = new publicjs.entityobj();
			eo.AttrList = {
				Name: "RolePurview",
				UseDistinct: true,
				OrgCode: "",
				UseBackUp: false,
				UseGroup: false,
			};
			eo.ValueList = {
				PurviewId: "PurviewId",
			};
			eo.QueryList = { RoleCode: this.currentRole.join(",") };
			ed.Data.Content.ObjectList.Object.push(eo);
			try {
				var returnValueStr = await this.$API.auth.objProcess.post(ed);
				var returnValue = JSON.parse(returnValueStr);
				// eslint-disable-next-line no-debugger
				debugger;
				if (returnValue.Result.OpFlag == "1") {
					let returnObj =
						returnValue.Result.Content.ObjectList.Object;
					let selectdata = [];
					for (let j = 0; j < returnObj.Rows.Row.length; j++) {
						selectdata.push(returnObj.Rows.Row[j].PurviewId);
					}
					this.$refs.treeRef.setCheckedKeys(selectdata, false);
					ed = null;
					eo = null;
					head = null;
				}
			} catch (error) {
				this.loading = false;
				//this.emptyText = error.statusText;
				return false;
			}
		},
		async loadUserOrg() {
			var head = new publicjs.head();
			publicjs.initHead(head, "query");
			// eslint-disable-next-line no-undef
			let ed = new publicjs.entitydata(head);
			var eo = new publicjs.entityobj();
			eo.AttrList = {
				Name: "UserRole",
				UseDistinct: true,
				OrgCode: "",
				UseBackUp: false,
				UseGroup: false,
			};
			eo.ValueList = {
				OrgCode: "OrgCode",
			};
			eo.QueryList = { UserCode: this.userCode };
			ed.Data.Content.ObjectList.Object.push(eo);
			try {
				var returnValueStr = await this.$API.auth.objProcess.post(ed);
				var returnValue = JSON.parse(returnValueStr);
				// eslint-disable-next-line no-debugger
				debugger;
				if (returnValue.Result.OpFlag == "1") {
					let returnObj =
						returnValue.Result.Content.ObjectList.Object.Rows.Row;
					this.currentOrgList = returnObj;
					//绑定有权限的机构
					if (this.currentOrgList && this.currentOrgList.length > 0) {
						for (let index in this.currentOrgList) {
							this.modifyTreeLabels(this.currentOrgList[index].OrgCode, this.$refs.tree.data);
						}
					}
					ed = null;
					eo = null;
					head = null;
				}
			} catch (error) {
				this.loading = false;
				//this.emptyText = error.statusText;
				return false;
			}
		},

		modifyTreeLabels(id, nodes = this.treeData) {
			nodes.forEach(node => {
				if (node.id == id) {
					node.label = "✔"+node.label  ; // 修改当前节点的label
				}
				else {
					if (node.children && node.children.length) {
						this.modifyTreeLabels(id, node.children); // 递归修改子节点
					}
				}
			});
		},
		async loadUserRole() {
			this.currentRole = [];
			var head = new publicjs.head();
			publicjs.initHead(head, "query");
			// eslint-disable-next-line no-undef
			let ed = new publicjs.entitydata(head);
			var eo = new publicjs.entityobj();
			eo.AttrList = {
				Name: "UserRole",
				UseDistinct: true,
				OrgCode: "",
				UseBackUp: false,
				UseGroup: false,
			};
			eo.ValueList = {
				RoleCode: "RoleCode",
			};
			eo.QueryList = {
				UserCode: this.userCode,
				OrgCode: this.currentOrgCode,
			};
			ed.Data.Content.ObjectList.Object.push(eo);
			try {
				var returnValueStr = await this.$API.auth.objProcess.post(ed);
				var returnValue = JSON.parse(returnValueStr);
				// eslint-disable-next-line no-debugger
				debugger;
				if (returnValue.Result.OpFlag == "1") {
					let returnObj =
						returnValue.Result.Content.ObjectList.Object.Rows.Row;
					if (returnObj && returnObj.length > 0) {
						for (let index in returnObj) {
							this.currentRole.push(returnObj[index].RoleCode);
						}
					}
					//加载角色(多个)的权限列表
					await this.LoadRolePurview();
					ed = null;
					eo = null;
					head = null;
				}
			} catch (error) {
				this.loading = false;
				//this.emptyText = error.statusText;
				return false;
			}
		},
		async submit() {
			this.isSaveing = true;
			//得到的数据this.entityObj
			// eslint-disable-next-line no-debugger
			debugger;
			var head = new publicjs.head();
			publicjs.initHead(head, "save");
			var ed = new publicjs.entitydata(head);
			var eo = new publicjs.entityobj();
			eo.AttrList = {
				Name: "UserInfo",
				DoType: "SetRole",
			};
			let isclearOrg = false; //判断是否清除机构*标记
			eo.ValueList = { Code: this.userCode, InLocal: "0" };
			eo.AttrList.BeforeSql =
				"delete from SystemUserRole where UserCode='" +
				this.userCode +
				"' and OrgCode='" +
				this.currentOrgCode +
				"';";
			if (this.currentRole.length > 0) {
				isclearOrg = false; //标识此机构下还有权限
				eo.SubObjectList = [];
				let subObjList = [];
				for (let i = 0; i < this.currentRole.length; i++) {
					let subeo = new publicjs.entityobj();
					subeo.AttrList = {
						Name: "UserRole",
						DoType: "Add",
					};
					subeo.ValueList = {
						Code:
							this.currentOrgCode +
							this.userCode +
							this.currentRole[i],
						OrgCode: this.currentOrgCode,
						UserCode: this.userCode,
						RoleCode: this.currentRole[i],
					};
					subObjList.push(subeo);
				}

				eo.SubObjectList.push({
					Name: "UserRole",
					SubObject: subObjList,
				});
			} else {
				isclearOrg = true; //标识此机构已经没有任何权限
				eo.AttrList.BeforeSql =
					"delete from SystemUserRole where UserCode='" +
					this.userCode +
					"' and OrgCode='" +
					this.currentOrgCode +
					"';";
			}
			ed.Data.Content.ObjectList.Object.push(eo);
			try {
				var returnValueStr = await this.$API.auth.objProcess.post(ed);
				console.log(returnValueStr);
				var returnValue = JSON.parse(returnValueStr);
				// eslint-disable-next-line no-debugger
				debugger;
				if (returnValue.Result.OpFlag == "1") {
					//清除此机构的有数据标识
					if (isclearOrg) {
						let orgobj = this.orgList.find(
							(e) => e.id == this.currentOrgCode
						);
						if (orgobj && orgobj.label.indexOf("*") > 0) {
							orgobj.label = orgobj.label.replace("*", "");
						}
					}
					//标记此机构的有数据标识(还没标记需要做标记)
					else {
						let orgobj = this.orgList.find(
							(e) => e.id == this.currentOrgCode
						);
						if (orgobj && orgobj.label.indexOf("*") < 0) {
							orgobj.label = orgobj.label + "*";
						}
					}
					this.$message.success("保存成功");
				} else {
					this.$message.error(returnValue.Result.OpMag);
				}
				// eslint-disable-next-line no-debugger
				//debugger;
				//var returnValue = JSON.parse(returnValueStr);
				//alert(returnValue.opFlag);
			} catch (error) {
				this.loading = false;
				//this.emptyText = error.statusText;
				return false;
			}
		},
		//加载树数据getGroup
		async getTree() {
			this.showGrouploading = true;
			var head = new publicjs.head();
			//publicjs.initHead(head, "query");
			publicjs.initHead(head, "orgtreenew");
			var ed = new publicjs.entitydata(head);
			var eo = new publicjs.entityobj();
			eo.AttrList = {
				Name: "Organize",
			};
			eo.ValueList = {
				Code: "id",
				Name: "label",
				ParentCode: "parentId",
				State: "State",
			};
			eo.QueryList = { State: "1" };
			eo.OrderList = { Code: "asc" };
			ed.Data.Content.ObjectList.Object.push(eo);
			try {
				var returnValueStr = await this.$API.auth.objProcess.post(ed);
				//alert(returnValueStr)
				var returnValue = JSON.parse(returnValueStr);
				let result = JSON.parse(returnValue.Result.Content);
				console.log(result);
				// eslint-disable-next-line no-debugger
				debugger;
				// var allNode = { id: "", label: "所有" };
				// result.unshift(allNode);
				this.group = result;
				this.showGrouploading = false;
			} catch (error) {
				this.showGrouploading = false;
				this.$alert(error.message, "提示", { type: "error" });
				return false;
			}
		},
		groupFilterNode(value, data) {
			if (!value) return true;
			return data.label.indexOf(value) !== -1;
		},
		//树点击事件
		groupClick(data) {
			// var params = {
			// 	groupId: data.id,
			// };
			// eslint-disable-next-line no-debugger
			//debugger
			if (data.id.length == 6) return;
			this.queryList.OrgCode = data.id;
			this.orgCode = data.id;
			this.orgName = data.label;
			this.opBindData();
		},
		handleNodeClick(data, checked) {
			// eslint-disable-next-line no-debugger
			debugger;
			// 如果已经选中了一个节点，则取消选择
			if (checked) {
				this.$refs.tree.setCheckedNodes([data]);
			}
			// 更新当前选中节点的 key
			//this.currentNodeKey = data;
			this.currentOrgCode = data.id;
			this.loadUserRole();
			// 其他业务逻辑
		}
	},
	async mounted() {
		await this.getTree();
		if(this.isOrgState){
			//初始化机构
			await this.loadOrgList();
		}
		//初始化角色
		await this.loadRoleList();
		//初始化权限树
		await this.loadPurviewTree();
		//加载个人授权机构
		await this.loadUserOrg();
		//加载收权机构的角色(可多个)
		await this.loadUserRole();
	},
};
</script>

<style lang="scss" scoped>
::v-deep .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
	background-color: #1890ff;
	border: 1px solid #1890ff;
	color: #fff
}
</style>
